package com.itbbfx.controller;

import com.itbbfx.entity.Menu;
import com.itbbfx.entity.TreeNode;
import com.itbbfx.entity.User;
import com.itbbfx.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/sel")
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(Model model, HttpSession session, User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginname(),user.getPwd());

        try{
            subject.login(token);
            User loginUser = userService.queryLoginUser(user.getLoginname());
            model.addAttribute("user", loginUser);
            model.addAttribute("loginname", loginUser.getLoginname());
            model.addAttribute("id", loginUser.getUserid());
            session.setAttribute("user", loginUser);
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg", "用户不存在！");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码错误！");
            return "login";
        }
    }

    @ResponseBody
    @RequestMapping("toTreeLoad")
    public List<TreeNode> toTreeLoad(HttpSession session){
        List<Menu> menuList = userService.queryUserRoleAuth(((User)(session.getAttribute("user"))).getType());

        List<TreeNode> nodes = new ArrayList<>();
        for(Menu menu : menuList){
            nodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),menu.getIcon()
                    ,menu.getHref(),menu.getSpread()==true,menu.getTarget()));
        }

        List<TreeNode> treeNodes = new ArrayList<>();

        for(TreeNode treeNode : nodes){
            if(treeNode.getPid() == 1){
                for (TreeNode node : nodes){
                    if(node.getPid() == treeNode.getId()){
                        treeNode.getChildren().add(node);
                    }
                }

                treeNodes.add(treeNode);
            }
        }

        return treeNodes;
    }
}